#include "headers/mainwindow.h"
#include "resources/forms/ui_mainwindow.h"
#include <QMouseEvent>
#include <QGraphicsDropShadowEffect>
#include <QDir>
#include <QDateTime>
MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow) {
    ui->setupUi(this);
    this->setWindowFlag(Qt::FramelessWindowHint); // 设置鼠标追踪，以便在鼠标不按下时也能接收鼠标移动事件
    setMouseTracking(true);
    //阴影边框效果
//    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
//    shadow->setBlurRadius(20);
//    shadow->setColor(Qt::red);
//    shadow->setOffset(0);
//    ui->centralWidget->setGraphicsEffect(shadow);
//    this->setAttribute(Qt::WA_TranslucentBackground);
    qApp->installEventFilter(this);
    ui->centralWidget->installEventFilter(this);
    ui->windnowIcon->setPixmap(QPixmap::fromImage(
            QImage("../../frameless-window/src/resources/images/logo.png")
                    .scaled(ui->windnowIcon->size(),
                            Qt::KeepAspectRatio, Qt::SmoothTransformation)));
    ui->minimizeBtn->setIcon(QIcon("../../frameless-window/src/resources/images/minimize.png"));
    ui->maximizeBtn->setIcon(QIcon("../../frameless-window/src/resources/images/maximize.png"));
    ui->closeBtn->setIcon(QIcon("../../frameless-window/src/resources/images/close.png"));
    ui->menuWidget->setStyleSheet("QMenuBar::item {color:white;} QMenuBar::item:selected { background: blue;color:white; } QMenuBar::item:pressed {  background: blue;color:white; }");

}

MainWindow::~MainWindow() {
    delete ui;
}


bool MainWindow::eventFilter(QObject *watched, QEvent *event) {

    if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (mouseEvent->button() == Qt::LeftButton) {
            // 如果鼠标按下位置位于窗口边缘，记录鼠标按下位置和窗口当前大小
            if (watched == this && !isInFrameSection(mouseEvent->pos(), Qt::NoSection)) {
//                qDebug() << "鼠标按下位置位于窗口边缘....";
                dragStartPosition = mouseEvent->globalPosition().toPoint();
                windowGeometry = geometry();
                frameSection = getEdgeSection(mouseEvent->pos());
                isResizing = true;
                return true; // 截取并处理该事件
            }
                // 如果鼠标按下位置位于 spacer 区域，记录鼠标按下位置
            else if (watched == ui->header && ui->headerSpacer->geometry().contains(mouseEvent->pos())) {
//                qDebug() << "鼠标按下位于 spacer 区域....";
                dragStartPosition = mouseEvent->globalPosition().toPoint() - frameGeometry().topLeft();
                isDragging = true;
                return true; // 截取并处理该事件
            }
        }
    } else if (event->type() == QEvent::MouseMove) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (watched->isWindowType()) {
            setCursorStyle(mouseEvent->pos());
        }
        if (mouseEvent->buttons() & Qt::LeftButton) {
            // 如果正在缩放窗口，计算新的窗口大小并移动
            if (watched->isWindowType() && isResizing) {
//                qDebug() << "正在缩放窗口....";
                QPoint delta = mouseEvent->globalPosition().toPoint() - dragStartPosition;
                if (frameSection == Qt::LeftSection) {
                    move(windowGeometry.topLeft() + QPoint(delta.x(), 0));
                    resize(windowGeometry.size() + QSize(-delta.x(), 0));
                } else if (frameSection == Qt::RightSection) {
                    resize(windowGeometry.size() + QSize(delta.x(), 0));
                } else if (frameSection == Qt::TopSection) {
                    resize(windowGeometry.size() + QSize(0, -delta.y()));
                    move(windowGeometry.topLeft() + QPoint(0, delta.y()));
                } else if (frameSection == Qt::BottomSection) {
                    resize(windowGeometry.size() + QSize(0, delta.y()));
                } else if (frameSection == Qt::TopLeftSection) {
                    resize(windowGeometry.size() + QSize(-delta.x(), -delta.y()));
                    move(windowGeometry.topLeft() + QPoint(delta.x(), delta.y()));
                } else if (frameSection == Qt::BottomRightSection) {
                    resize(windowGeometry.size() + QSize(delta.x(), delta.y()));
                } else if (frameSection == Qt::BottomLeftSection) {
                    resize(windowGeometry.size() + QSize(-delta.x(), delta.y()));
                    move(windowGeometry.topLeft() + QPoint(delta.x(), 0));
                } else if (frameSection == Qt::TopRightSection) {
                    resize(windowGeometry.size() + QSize(delta.x(), -delta.y()));
                    move(windowGeometry.topLeft() + QPoint(0, delta.y()));
                }
//                qDebug() << "width" << this->size().width();
//                qDebug() << "height" << this->size().height();
                if (this->size().width() <= 300) {
                    this->resize(300, this->size().height());
                }
                if (this->size().height() <= 50) {
                    this->resize(this->size().width(), 50);
                }
                return true; // 截取并处理该事件
            } else if (isDragging) {
//                qDebug() << "正在拖动 spacer 区域....";
                // 如果正在拖动 spacer 区域，移动窗口
                QPoint newPos = mouseEvent->globalPosition().toPoint() - dragStartPosition;
                move(newPos);
                return true; // 截取并处理该事件
            }
        }
    } else if (event->type() == QEvent::MouseButtonRelease) {
//        qDebug() << "MouseButtonRelease....";
        isDragging = false;
        isResizing = false;
        if (watched == ui->header){
            if (currentTimeStamp>0){
                bool dbClick = isHeadDBClick(QDateTime::currentDateTime().currentMSecsSinceEpoch());
                currentTimeStamp = 0;
                if (dbClick){
//                    qDebug() << "双击了";
                    headDBClick();
                }
//                qDebug() << "是否双击"<<dbClick;
//                qDebug() << "currentTimeStamp" << currentTimeStamp;
            } else{
//                qDebug() << "currentTimeStamp赋值";
                currentTimeStamp = QDateTime::currentDateTime().currentMSecsSinceEpoch();
            }

        }
    }

    return QWidget::eventFilter(watched, event); // 其他事件交给父类处理
}

bool MainWindow::isInFrameSection(const QPoint &pos, Qt::WindowFrameSection edge) {
    QRect area = QRect(0, 0, width(), height()).adjusted(distance, distance, -distance, -distance);
    if (edge == Qt::NoSection) { // center包含于edge包含于corner，判断顺序必须是 center>edge>corner
        return area.contains(pos);
    }
    if (edge == Qt::LeftSection || edge == Qt::TopLeftSection || edge == Qt::BottomLeftSection) {
        area.adjust(-distance * 2, 0, 0, 0); // 乘2是为了增加偏移量，超出窗体边缘，避免光标抖动
    }
    if (edge == Qt::RightSection || edge == Qt::TopRightSection || edge == Qt::BottomRightSection) {
        area.adjust(0, 0, distance * 2, 0);
    }
    if (edge == Qt::TopSection || edge == Qt::TopLeftSection || edge == Qt::TopRightSection) {
        area.adjust(0, -distance * 2, 0, 0);
    }
    if (edge == Qt::BottomSection || edge == Qt::BottomLeftSection || edge == Qt::BottomRightSection) {
        area.adjust(0, 0, 0, distance * 2);
    }
    return area.contains(pos);
}


Qt::WindowFrameSection MainWindow::getEdgeSection(const QPoint &pos) {
    QList<Qt::WindowFrameSection> sections = {Qt::NoSection, Qt::LeftSection, Qt::RightSection, Qt::TopSection,
                                              Qt::BottomSection,
                                              Qt::TopLeftSection, Qt::TopRightSection, Qt::BottomLeftSection,
                                              Qt::BottomRightSection};
    for (Qt::WindowFrameSection section : sections) {
        if (isInFrameSection(pos, section)) {
            return section;
        }
    }
    return Qt::NoSection;
}

void MainWindow::setCursorStyle(const QPoint &pos) {
    Qt::WindowFrameSection frameSection = getEdgeSection(pos);
    if (frameSection == Qt::NoSection) {
        setCursor(Qt::ArrowCursor);
    } else if (frameSection == Qt::LeftSection || frameSection == Qt::RightSection) {
        setCursor(Qt::SizeHorCursor);
    } else if (frameSection == Qt::TopSection || frameSection == Qt::BottomSection) {
        setCursor(Qt::SizeVerCursor);
    } else if (frameSection == Qt::TopLeftSection || frameSection == Qt::BottomRightSection) {
        setCursor(Qt::SizeFDiagCursor);
    } else if (frameSection == Qt::TopRightSection || frameSection == Qt::BottomLeftSection) {
        setCursor(Qt::SizeBDiagCursor);
    }
}

void MainWindow::on_closeBtn_clicked() {
    qDebug() << "点击了关闭";
    close();
}

void MainWindow::on_maximizeBtn_clicked() {
    qDebug() << "点击了最大化";
    if (isMaximized()) showNormal();
    else showMaximized();
}

void MainWindow::on_minimizeBtn_clicked() {
    qDebug() << "点击了最小化";
    showMinimized();
}
void MainWindow::headDBClick(){
    qDebug() << "双击了head";
    if (isMaximized()) showNormal();
    else showMaximized();
}
bool MainWindow:: isHeadDBClick(long long timestamp){
//    qDebug () << "currentTimeStamp" << currentTimeStamp;
//    qDebug () << "timestamp" << timestamp;
    if (timestamp - currentTimeStamp >= 500){
        return false;
    }
    return true;
}